﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using KeaoBase;
using System.Threading;

namespace KeaoMDS.Listener
{
    public partial class YaoKongFuJian : BaseForm
    {
        public YaoKongFuJian(DataGridViewSelectedRowCollection Rows)
        {
            InitializeComponent();
            m_Rows = Rows;
        }

        public YaoKongFuJian(DataTable Dt)
        {
            InitializeComponent();
            m_Dt = Dt;
        }
        private DataTable m_Dt;
        private DataGridViewSelectedRowCollection m_Rows;
        private Socket m_Socket;
        private byte[] m_SocketReadBytes = new byte[1024];
        private int m_YiBiaoDuShu;
        private bool m_WenDing;
        private decimal m_BeiChuShu = Convert.ToDecimal(KeaoUtils.ConfigGetNodeAttr("称重设备", "被除数"));
        private decimal m_DangQianZhongLiang;
        private Thread m_SendDataThread;

        private void YaoKongFuJian_Load(object sender, EventArgs e)
        {
            try
            {
                m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_Socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));
                m_Socket.BeginReceive(m_SocketReadBytes, 0, 1024, SocketFlags.None, OnReadSocketBytes, 0);

                Tmr_UI.Interval = 1000;
                Tmr_UI.Tick += new EventHandler(Tmr_UI_Tick);

                m_SendDataThread = new Thread(new ThreadStart(SendData));
                m_SendDataThread.Start();
                
            }
            catch
            {
                KeaoUtils.ShowInfoMessage("仪表服务未连接，请检查重试。");
                this.Close();
            }
        }

        private void SendData()
        {
            try
            {
                if (m_Rows != null)
                {
                    foreach (DataGridViewRow row in m_Rows)
                    {
                        MainForm.m_Listener.SendData(string.Format("{0}", row.Cells["col_jianceshuju"]));
                        Thread.Sleep(3000);
                        TableRow editRow = new TableRow() { TableName = "tbl_yaokongjiance", ID = string.Format("{0}", row.Cells["col_id"]), Ctl = DBCtl.修改 };
                        editRow.DataCols.Add(new TableCol() { ColName = "yingxiangzhongliang", ValueMember = m_DangQianZhongLiang, ValueType = DataValueCommonType.数字 });
                        editRow.DataCols.Add(new TableCol() { ColName = "shujufujian", ValueMember = "已复检", ValueType = DataValueCommonType.字符串 });
                        KeaoUtils._DB.SaveTableRows(editRow);
                    }
                }

                if (m_Dt != null)
                {
                    foreach (DataRow row in m_Dt.Rows)
                    {
                        if (row["shujufujian"].Equals("已复检"))
                        {
                            continue;
                        }

                        MainForm.m_Listener.SendData(string.Format("{0}", row["jianceshuju"]));
                        Thread.Sleep(3000);
                        TableRow editRow = new TableRow() { TableName = "tbl_yaokongjiance", ID = string.Format("{0}", row["id"]), Ctl = DBCtl.修改 };
                        editRow.DataCols.Add(new TableCol() { ColName = "yingxiangzhongliang", ValueMember = m_DangQianZhongLiang, ValueType = DataValueCommonType.数字 });
                        editRow.DataCols.Add(new TableCol() { ColName = "shujufujian", ValueMember = "已复检", ValueType = DataValueCommonType.字符串 });
                        KeaoUtils._DB.SaveTableRows(editRow);
                    }
                }
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("发送复检数据异常。{0}", err.Message));
            }
        }

        private int m_Interval = 0;

        void Tmr_UI_Tick(object sender, EventArgs e)
        {
            try
            {
                m_DangQianZhongLiang = m_YiBiaoDuShu / m_BeiChuShu;
                u_weight1.SetNumber(m_DangQianZhongLiang.ToString("0.00"), m_WenDing);//显示重量到界面
                string sendStr = (m_DangQianZhongLiang * 1000m).ToString("0");
                m_Socket.Send(Encoding.Default.GetBytes(sendStr));

                label1.Text = string.Format("正在进行监测，请稍候...{0}", m_Interval++);
                if (m_SendDataThread.ThreadState != ThreadState.Running)
                {
                    Tmr_UI.Stop();
                    Tmr_UI.Enabled = false;
                    this.Close();
                }
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("监测复检刷新数据异常。{0}", err.Message));
            }
        }


        private void OnReadSocketBytes(IAsyncResult Args)
        {
            try
            {
                m_Socket.EndReceive(Args);
                m_YiBiaoDuShu = BitConverter.ToInt32(m_SocketReadBytes, 0);
                if (m_SocketReadBytes[4] == 0x01)
                {
                    m_WenDing = false;
                }
                else
                {
                    m_WenDing = true;
                }

                while (true)
                {
                    m_Socket.Receive(m_SocketReadBytes, 0, m_SocketReadBytes.Length, SocketFlags.None);
                    m_YiBiaoDuShu = BitConverter.ToInt32(m_SocketReadBytes, 0);
                    if (m_SocketReadBytes[4] == 0x01)
                    {
                        m_WenDing = false;
                    }
                    else
                    {
                        m_WenDing = true;
                    }
                }
            }
            catch (Exception)
            {
                return;
            }
        }

        private void YaoKongFuJian_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (m_Socket != null)
                {
                    m_Socket.Shutdown(SocketShutdown.Both);
                    m_Socket.Close();
                }
                if (m_SendDataThread.ThreadState == ThreadState.Running)
                {
                    m_SendDataThread.Abort();
                }
            }
            catch
            {
                return;
            }
        }
    }
}
